from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import binascii

class AESUtil:
    @staticmethod
    def bytes_to_hex(b_arr):
        return ''.join(f'{b:02x}' for b in b_arr)

    @staticmethod
    def hex_to_byte(c):
        return int(c, 16)

    @staticmethod
    def decrypt_str(ciphertext, key):
        return AESUtil.decrypt(ciphertext, key.encode('utf-8')).decode('utf-8')

    @staticmethod
    def decrypt(ciphertext, key):
        try:
            cipher = AES.new(key, AES.MODE_ECB)
            decrypted = cipher.decrypt(AESUtil.hex_to_bytes(ciphertext))
            return unpad(decrypted, AES.block_size)
        except Exception as e:
            print(e)
            raise RuntimeError(e)

    @staticmethod
    def encrypt_str(plaintext, key):
        return AESUtil.bytes_to_hex(AESUtil.encrypt(plaintext, key.encode('utf-8')))

    @staticmethod
    def encrypt(plaintext, key):
        try:
            cipher = AES.new(key, AES.MODE_ECB)
            padded = pad(plaintext.encode('utf-8'), AES.block_size)
            return cipher.encrypt(padded)
        except Exception as e:
            print(e)
            raise RuntimeError(e)

   

    @staticmethod
    def hex_to_bytes(hex_str):
        hex_str = hex_str.upper()
        length = len(hex_str) // 2
        b_arr = bytearray(length)
        for i in range(length):
            pos = i * 2
            b_arr[i] = (AESUtil.hex_to_byte(hex_str[pos]) << 4) | AESUtil.hex_to_byte(hex_str[pos+1])
        return bytes(b_arr)
